import createError from 'http-errors';
import express from 'express';
import path from 'path';
import cookieParser from 'cookie-parser';
import logger from 'morgan';
import mysql from 'mysql';
import fs from 'fs';

import indexRouter from './routes/index.js';
import usersRouter from './routes/users.js';
import adminsRouter from './routes/admins.js';

import { verToken } from './controller/Component/token.js';
import expressJwt from 'express-jwt';
import { mysqlConnectPromise, mysqlQueryPromise } from './controller/Component/MySQLPromise.js';
import multer from 'multer';
import { server } from './server.js';

const __dirname = path.resolve();

var app = express();

app.locals.pool = mysql.createPool({
  host: 'localhost',
  port: 3306,
  user: 'root',
  password: '0xSQL5A57',
  database: 'Food',
  acquireTimeout: 10000,
  connectTimeout: 10000,
  connectionLimit: 5
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

app.use(multer({ dest: './public/file/' }).any());
app.use(express.static(path.join(__dirname, 'public')));

app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length,Authorization,Accept,X-Requested-With,ContentType");
  res.header("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE");
  next();
})

// 解析token获取用户信息
app.use(function (req, res, next) {

  var token = req.headers['authorization'];

  if (token == undefined) {
    return next();
  } else {
    verToken(token).then(async (data) => {
      req.data = data;
      let pool = req.app.locals.pool;
      let connection = await mysqlConnectPromise(pool);
      let today = new Date().toLocaleDateString().replaceAll('/', '-');
      await mysqlQueryPromise(connection, `update dailyBrowse set browseTimes=browseTimes+1 where today = '${today}'`);
      connection.release();
      return next();
    }).catch((error) => {
      return next();
    })
  }

});

//验证token是否过期并规定哪些路由不用验证
app.use(expressJwt({
  secret: 'mes_qdhd_mobile_xhykjyxgs',
  algorithms: ['HS256']
}).unless({
  path: ['/users', '/users/all', '/signin', '/signup', '/admins/signin', '/', '/resetpass', '/fileupload']//除了这个地址，其他的URL都需要验证
}));

// 路由
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/admins', adminsRouter);

app.use(function (err, req, res, next) {
  if (err.name === 'UnauthorizedError') {
    res.status(401).send('invalid token')
  }
});

app.post('/fileuploadt', function async(req, res) {
  console.log(req.body);
  const filename = req.files[0].path + path.parse(req.files[0].originalname).ext
  fs.rename(req.files[0].path, filename, function (err) {
    if (err) {
      console.log(err);
      res.send('error');
    } else {
      let fname = path.parse(filename).base;
      res.send(server + '/file/' + fname);
    }
  })
})

app.use(function (req, res, next) {
  next(createError(404));
});

app.use(function (err, req, res, next) {

  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  res.status(err.status || 200);
  res.render('error');

});

export default app;